"""
HiAgent Chat SDK 使用示例

本文件包含了HiAgent Chat SDK的各种使用示例，帮助开发者快速上手。
"""

import asyncio
import time
from typing import List, Dict, Any

from .client import HiAgentClient
from .config import HiAgentConfig, load_config
from .models import Conversation, Message, QueryExtends, FileInfo
from .exceptions import HiAgentException


def basic_usage_example():
    """基础使用示例"""
    print("=== 基础使用示例 ===")
    
    # 1. 配置客户端
    config = HiAgentConfig(
        app_key="your_app_key_here",
        base_url="https://api.hiagent.com"
    )
    
    client = HiAgentClient(config)
    user_id = "test_user_123"
    
    try:
        # 2. 创建会话
        conversation = client.create_conversation(
            user_id=user_id,
            title="测试会话",
            description="这是一个测试会话"
        )
        print(f"创建会话成功: {conversation.id}")
        
        # 3. 发送消息
        response = client.chat(
            conversation_id=conversation.id,
            user_id=user_id,
            query="你好，请介绍一下你自己"
        )
        print(f"AI回复: {response.content}")
        
        # 4. 获取会话列表
        conversations = client.get_conversation_list(user_id)
        print(f"会话数量: {len(conversations)}")
        
    except HiAgentException as e:
        print(f"发生错误: {e}")


def streaming_chat_example():
    """流式聊天示例"""
    print("\n=== 流式聊天示例 ===")
    
    config = HiAgentConfig(app_key="your_app_key_here")
    client = HiAgentClient(config)
    user_id = "test_user_123"
    
    try:
        # 创建会话
        conversation = client.create_conversation(
            user_id=user_id,
            title="流式聊天测试"
        )
        
        # 流式聊天
        print("AI回复: ", end="", flush=True)
        for chunk in client.chat_stream(
            conversation_id=conversation.id,
            user_id=user_id,
            query="请写一首关于春天的诗"
        ):
            print(chunk, end="", flush=True)
        print()  # 换行
        
    except HiAgentException as e:
        print(f"发生错误: {e}")


def advanced_chat_example():
    """高级聊天示例（带文件和扩展参数）"""
    print("\n=== 高级聊天示例 ===")
    
    config = HiAgentConfig(app_key="your_app_key_here")
    client = HiAgentClient(config)
    user_id = "test_user_123"
    
    try:
        # 创建会话
        conversation = client.create_conversation(
            user_id=user_id,
            title="高级聊天测试"
        )
        
        # 准备文件信息
        files = [
            FileInfo(
                file_id="file_123",
                file_name="document.pdf",
                file_type="pdf",
                file_size=1024000
            )
        ]
        
        # 准备扩展参数
        query_extends = QueryExtends(
            files=files,
            extra_params={"temperature": 0.7, "max_tokens": 1000}
        )
        
        # 发送带文件的消息
        response = client.chat(
            conversation_id=conversation.id,
            user_id=user_id,
            query="请分析这个PDF文档的内容",
            query_extends=query_extends
        )
        print(f"AI回复: {response.content}")
        
    except HiAgentException as e:
        print(f"发生错误: {e}")


def conversation_management_example():
    """会话管理示例"""
    print("\n=== 会话管理示例 ===")
    
    config = HiAgentConfig(app_key="your_app_key_here")
    client = HiAgentClient(config)
    user_id = "test_user_123"
    
    try:
        # 创建多个会话
        conversations = []
        for i in range(3):
            conv = client.create_conversation(
                user_id=user_id,
                title=f"测试会话 {i+1}",
                description=f"这是第{i+1}个测试会话"
            )
            conversations.append(conv)
            print(f"创建会话: {conv.title}")
        
        # 获取会话列表
        conv_list = client.get_conversation_list(user_id)
        print(f"总会话数: {len(conv_list)}")
        
        # 置顶第一个会话
        client.set_conversation_top(conversations[0].id, user_id)
        print(f"置顶会话: {conversations[0].title}")
        
        # 更新会话标题
        client.update_conversation(
            conversation_id=conversations[1].id,
            user_id=user_id,
            title="更新后的标题",
            description="更新后的描述"
        )
        print(f"更新会话: {conversations[1].id}")
        
        # 删除最后一个会话
        client.delete_conversation(conversations[2].id, user_id)
        print(f"删除会话: {conversations[2].title}")
        
    except HiAgentException as e:
        print(f"发生错误: {e}")


def message_management_example():
    """消息管理示例"""
    print("\n=== 消息管理示例 ===")
    
    config = HiAgentConfig(app_key="your_app_key_here")
    client = HiAgentClient(config)
    user_id = "test_user_123"
    
    try:
        # 创建会话
        conversation = client.create_conversation(
            user_id=user_id,
            title="消息管理测试"
        )
        
        # 发送几条消息
        messages = []
        for i in range(3):
            response = client.chat(
                conversation_id=conversation.id,
                user_id=user_id,
                query=f"这是第{i+1}条测试消息"
            )
            messages.append(response)
            print(f"发送消息 {i+1}: {response.content[:50]}...")
        
        # 获取会话消息历史
        history = client.get_conversation_messages(
            conversation_id=conversation.id,
            user_id=user_id,
            limit=10
        )
        print(f"消息历史数量: {len(history)}")
        
        # 对第一条消息点赞
        if messages:
            client.feedback_message(
                message_id=messages[0].id,
                user_id=user_id,
                feedback="like"
            )
            print("对消息点赞成功")
        
        # 获取提问建议
        suggestions = client.get_suggested_questions(
            conversation_id=conversation.id,
            user_id=user_id
        )
        print(f"提问建议: {suggestions}")
        
    except HiAgentException as e:
        print(f"发生错误: {e}")


def workflow_example():
    """工作流示例"""
    print("\n=== 工作流示例 ===")
    
    config = HiAgentConfig(app_key="your_app_key_here")
    client = HiAgentClient(config)
    user_id = "test_user_123"
    
    try:
        # 异步运行工作流
        inputs = {
            "input_text": "请分析这段文本的情感",
            "language": "zh-CN"
        }
        
        task_id = client.run_workflow_async(
            user_id=user_id,
            inputs=inputs
        )
        print(f"工作流任务ID: {task_id}")
        
        # 查询工作流进度
        while True:
            result = client.query_workflow_progress(task_id, user_id)
            print(f"工作流状态: {result.status}")
            
            if result.status in ["completed", "failed"]:
                if result.status == "completed":
                    print(f"工作流结果: {result.output}")
                else:
                    print(f"工作流失败: {result.error}")
                break
            
            time.sleep(2)  # 等待2秒后再查询
        
        # 同步运行工作流
        sync_result = client.run_workflow_sync(
            user_id=user_id,
            inputs=inputs
        )
        print(f"同步工作流结果: {sync_result.output}")
        
    except HiAgentException as e:
        print(f"发生错误: {e}")


def memory_management_example():
    """长期记忆管理示例"""
    print("\n=== 长期记忆管理示例 ===")
    
    config = HiAgentConfig(app_key="your_app_key_here")
    client = HiAgentClient(config)
    user_id = "test_user_123"
    
    try:
        # 获取长期记忆列表
        memories = client.list_long_memory(user_id)
        print(f"当前记忆数量: {len(memories)}")
        
        # 如果有记忆，更新第一个
        if memories:
            memory = memories[0]
            client.update_long_memory(
                memory_id=memory.id,
                user_id=user_id,
                content="更新后的记忆内容"
            )
            print(f"更新记忆: {memory.id}")
        
        # 获取用户变量
        variables = client.get_user_variables(user_id)
        print(f"用户变量数量: {len(variables)}")
        
        # 设置用户变量
        client.set_user_variables(
            user_id=user_id,
            variables={
                "preferred_language": "zh-CN",
                "timezone": "Asia/Shanghai"
            }
        )
        print("设置用户变量成功")
        
    except HiAgentException as e:
        print(f"发生错误: {e}")


def error_handling_example():
    """错误处理示例"""
    print("\n=== 错误处理示例 ===")
    
    config = HiAgentConfig(
        app_key="invalid_key",  # 故意使用无效的key
        base_url="https://api.hiagent.com"
    )
    
    client = HiAgentClient(config)
    user_id = "test_user_123"
    
    try:
        # 尝试创建会话（应该会失败）
        conversation = client.create_conversation(
            user_id=user_id,
            title="错误测试会话"
        )
        
    except Exception as e:
        print(f"捕获到错误: {type(e).__name__}: {e}")
        
        # 根据错误类型进行不同处理
        if "authentication" in str(e).lower():
            print("认证失败，请检查APP_KEY")
        elif "network" in str(e).lower():
            print("网络错误，请检查网络连接")
        else:
            print("其他错误，请查看详细信息")


def configuration_example():
    """配置示例"""
    print("\n=== 配置示例 ===")
    
    # 方式1：直接创建配置
    config1 = HiAgentConfig(
        app_key="your_app_key",
        base_url="https://api.hiagent.com",
        timeout=60,
        max_retries=5
    )
    print(f"配置1 - 超时时间: {config1.timeout}秒")
    
    # 方式2：从环境变量加载配置
    # 需要设置环境变量: HIAGENT_APP_KEY, HIAGENT_BASE_URL 等
    config2 = HiAgentConfig.from_env()
    print(f"配置2 - 基础URL: {config2.base_url}")
    
    # 方式3：从字典创建配置
    config_dict = {
        "app_key": "your_app_key",
        "base_url": "https://api.hiagent.com",
        "timeout": 30,
        "custom_param": "custom_value"
    }
    config3 = HiAgentConfig.from_dict(config_dict)
    print(f"配置3 - 自定义参数: {config3.extra_config}")
    
    # 方式4：使用全局配置管理器
    load_config(config1)
    client = HiAgentClient()  # 自动使用全局配置
    print("使用全局配置创建客户端成功")


def main():
    """运行所有示例"""
    print("HiAgent Chat SDK 使用示例")
    print("=" * 50)
    
    # 注意：运行示例前需要设置有效的APP_KEY
    examples = [
        basic_usage_example,
        streaming_chat_example,
        advanced_chat_example,
        conversation_management_example,
        message_management_example,
        workflow_example,
        memory_management_example,
        error_handling_example,
        configuration_example
    ]
    
    for example in examples:
        try:
            example()
        except Exception as e:
            print(f"示例 {example.__name__} 执行失败: {e}")
        
        print("-" * 30)


if __name__ == "__main__":
    main()